<?php
// +----------------------------------------------------------------------
// | likeshop开源商城系统
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码，建议反馈是我们前进的动力
// | gitee下载：https://gitee.com/likeshop_gitee
// | github下载：https://github.com/likeshop-github
// | 访问官网：https://www.likeshop.cn
// | 访问社区：https://home.likeshop.cn
// | 访问手册：http://doc.likeshop.cn
// | 微信公众号：likeshop技术社区
// | likeshop系列产品在gitee、github等公开渠道开源版本可免费商用，未经许可不能去除前后端官方版权标识
// |  likeshop系列产品收费版本务必购买商业授权，购买去版权授权后，方可去除前后端官方版权标识
// | 禁止对系统程序代码以任何目的，任何形式的再发布
// | likeshop团队版权所有并拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeshop.cn.team
// +----------------------------------------------------------------------


namespace app\api\logic;


use app\api\service\JwtAuth;
use app\api\service\UserServer;
use app\common\model\Users;
use app\common\model\WeChat;

use app\common\service\WeChatServer;
use EasyWeChat\Kernel\Exceptions\Exception;
use EasyWeChat\Kernel\Messages\Text;
use EasyWeChat\Factory;
use think\Db;


class WeChatLogic
{

    protected function get_app()
    {
        return [
            'app_id' => "wxe474bb1488d38822",
            'secret' => "fe854cfe722195c8c4c9fec2a0d505a3",
            // 下面为可选项
            // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
            'response_type' => 'array',

            'log' => [
                'driver' => 'daily',
                'level' => 'debug', //info  'driver' => 'daily',
                'file' => __DIR__.'/../../../runtime/wechat.log',
            ],
        ];
    }

    public static function mnpLogin($params)
    {
        try {
            $app = Factory::miniProgram($this->get_app());
            $code = $params['code'];
            $response = $app->auth->session($code);
            if (!isset($response['openid']) || empty($response['openid'])) {
                return data_error('获取openID失败');
            }
            $user_id = Db::name('users_auth')->alias('au')
                ->join('users u', 'au.user_id=u.id')
                ->where(function ($query) use ($response) {
                    $query->whereOr(['au.openid' => $response['openid']]);
                    if (isset($response['unionid']) && !empty($response['unionid'])) {
                        $query->whereOr(['au.unionid' => $response['unionid']]);
                    }
                })
                ->value('user_id');
            if (empty($user_id)) {
                $user_info = UserServer::createUser($response, 1);
            } else {
                $user_info = UserServer::updateUser($response, 1, $user_id);
            }
            if (empty($user_info)) {
                return data_error('登录失败');
            }

            if ($user_info['status'] != 1) {
                return data_error('用户状态异常');
            }
            $user_info['token'] = JwtAuth::getInstance()->getToken([
                'user_id' => $user_info['id'],
                'user_name' => $user_info['username'] ?? 'user_' . $user_info['id']
            ]);
            unset($user_info['id']);
            unset($user_info['status']);
            return data_success('登录成功', $user_info);
        } catch (Exception $e) {
            return data_error('登录失败' . $e->getMessage());
        }
    }

    public static function getMobileByMnp($params)
    {
        $app = Factory::miniProgram($this->get_app());
        $code = $params['code'];
        $response = $app->auth->session($code);
        if (!isset($response['session_key'])) {
            return data_error('获取openID失败');
        }
        $user_id = self::getUid();
        $response = $app->encryptor->decryptData($response['session_key'], $params['iv'], $params['encrypted_data']);
        $isExist = Users::where([
            ['mobile', '=', $response['phoneNumber']],
            ['id', '<>', $user_id]
        ])->find();
        if (!empty($isExist)) {
            return data_error('手机号已被其他账号绑定');
        }
        Users::where(['id' => $user_id])->update(['mobile' => $response['phoneNumber']]);
        return data_success('获取成功');

    }
    /**
     * 获取微信配置
     * @param $url
     * @return array|string
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \EasyWeChat\Kernel\Exceptions\RuntimeException
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public static function jsConfig($url)
    {
        $config = WeChatServer::getOaConfig();
        $app = Factory::officialAccount($config);
        $url = urldecode($url);
        $app->jssdk->setUrl($url);
        $apis = [
            'onMenuShareTimeline',
            'onMenuShareAppMessage',
            'onMenuShareQQ',
            'onMenuShareWeibo',
            'onMenuShareQZone',
            'openLocation',
            'getLocation',
            'chooseWXPay',
            'updateAppMessageShareData',
            'updateTimelineShareData',
            'openAddress',
            'scanQRCode'
        ];
        try {
            $data = $app->jssdk->getConfigArray($apis, $debug = false, $beta = false);
            return data_success('', $data);
        } catch (Exception $e) {
            return data_error('公众号配置出错' . $e->getMessage());
        }
    }

    public static function index($params)
    {

        if (isset($params['echostr'])) {
            echo $params["echostr"];
            exit;
        }
        //微信配置
        $config = WeChatServer::getOaConfig();
        $app = Factory::officialAccount($config);

        $app->server->push(function ($message) {
            switch ($message['MsgType']) {
                case WeChat::msg_type_event: //关注事件
                    switch ($message['Event']) {
                        case WeChat::msg_event_subscribe:
                            $reply_content = Db::name('wechat_reply')
                                ->where(['reply_type' => WeChat::msg_event_subscribe, 'status' => 1, 'del' => 0])
                                ->value('content');
                            //关注回复空的话，找默认回复
                            if (empty($reply_content)) {
                                $reply_content = Db::name('wechat_reply')
                                    ->where(['reply_type' => WeChat::msg_type_default, 'status' => 1, 'del' => 0])
                                    ->value('content');
                            }
                            if ($reply_content) {
                                $text = new Text($reply_content);
                                return $text;
                            }
                            break;
                        case WeChat::msg_event_click: // 点击事件
                            $reply_content = Db::name('wechat_reply')->where([
                                'reply_type' => WeChat::msg_type_text,
                                'status' => 1,
                                'del' => 0,
                                'keyword' => $message['EventKey']
                            ])->value('content');
                            if (!empty($reply_content)) {
                                $text = new Text($reply_content);
                                return $text;
                            }
                            break;
                    }

                case WeChat::msg_type_text://消息类型
                    $reply_list = Db::name('wechat_reply')
                        ->where(['reply_type' => WeChat::msg_type_text, 'status' => 1, 'del' => 0])
                        ->order('sort asc')
                        ->select();
                    $reply_content = '';
                    foreach ($reply_list as $reply) {
                        switch ($reply['matching_type']) {
                            case 1://全匹配
                                $reply['keyword'] === $message['Content'] && $reply_content = $reply['content'];
                                break;
                            case 2://模糊匹配
                                stripos($reply['keyword'], $message['Content']) !== false && $reply_content = $reply['content'];
                                break;
                        }
                    }
                    //消息回复为空的话，找默认回复
                    if (empty($reply_content)) {
                        $reply_content = Db::name('wechat_reply')
                            ->where(['reply_type' => WeChat::msg_type_default, 'status' => 1, 'del' => 0])
                            ->value('content');
                    }
                    if ($reply_content) {
                        $text = new Text($reply_content);
                        return $text;
                    }
                    break;


            }
        });
        $response = $app->server->serve();
        $response->send();

    }

}